let data = require("./data");
// data = [data[0]];
const tpl = `
<div class="list-item {{status_style}}">
    <img class="list-item__logo" src="{{logo_url}}" alt="windows" class="logo">
    <div class="list-item__content">
        <div class="list-item__info">
            <span class="list-item__detail"><i class="icon-desktop"></i><a href="#">{{domin}}</a></span>
            <span class="list-item_badge badge {{badge_style}}">{{status}}</span>
            <span class="list-item__detail"><i class="icon-info"></i>{{ip}}</span>
            <span class="list-item__detail"><i class="icon-folder"></i>{{path}}</span>
        </div>
        <div class="list-item__action">
            <div class="list-item__add">
                <button class="list-item__add__btn btn btn-blue" data-id="{{id}}"><i class="icon-plus"></i></button>
                <span class="list-item__add__item">
                  {{#agents}}
                  <span>{{.}}<i data-id="{{id}}" data-agent="{{.}}" class="list-item__del__btn icon-trash"></i></span>
                  {{/agents}}                   
                </span>
            </div>
            {{deny_btn}}
        </div>
    </div>
</div>`;

const render = function(tpl, data) {
  // match {{name}}
  let regexp = /\{\{([\w.]+)\}\}/g;
  // match "{{#agents}}<b>{{.}}</b>{{/agents}}"
  let regSection = /\{\{#(\w+)}\}([\S\s]*)\{\{\/\1\}\}/g;
  let result = data.map(item => {
    item.logo_url = "@/img/os-icons/" + item.logo + ".png"
    item.status_style = "list-item--" + item.status;
    item.badge_style = "badge-" + (item.status === "idle" ? "green" : "yellow");
    item.deny_btn =
      item.status === "idle"
        ? ""
        : `<button class="btn btn-blue list-item__deny"><i class="icon-deny"></i>Deny</button>`;

    return tpl.replace(regSection, function(match, p1, p2) {
      let tmpHtml = ''      
      let currentValue = item[p1] || []
      currentValue.forEach(child => {
        tmpHtml += p2.replace(regexp, function(match, p1){
          if (p1 === '.') {
            return child
          } else {
            return match
          }
        })
      })
      return tmpHtml;
    }).replace(regexp, function(match, p1) {
      return item[p1] || ''
    })
  });
  return result.join("\n");
};

console.log(render(tpl, data));